<?php

require __DIR__ . '/vendor/autoload.php';
require_once __DIR__ . '/app/config/define.php';

use Core\BeanFactory;
use Core\http\Request;
use Core\http\Response;
use Core\init\RouterCollect;


BeanFactory::init();
$dispatcher = BeanFactory::getBean(RouterCollect::class)->getDispatcher();

$server = new \Swoole\Http\Server('0.0.0.0', 9501);

$server->on("request", function (\Swoole\Http\Request $request, \Swoole\Http\Response $response) use ($dispatcher) {
//    var_dump($request->get, $request->post);
//    $response->end("Hello frans");

    //swoole 原生 判断 uri 确定访问路径
//    if ($request->server["request_uri"] == '/test') {
//        $response->end("__TEST___");
//    }

    //fastroute 结合swoole  做request dispatcher
    /*$routeInfo = $dispatcher->dispatch($request->server["request_method"], $request->server['request_uri']);
    switch ($routeInfo[0]) {
        case FastRoute\Dispatcher::NOT_FOUND:
            $response->status(404);
            $response->end("Method not found");
            break;
        case FastRoute\Dispatcher::METHOD_NOT_ALLOWED:
            $response->status(405);
            $response->end("Method not allow");

            break;
        case FastRoute\Dispatcher::FOUND:
            $handler = $routeInfo[1];

            $response->end($handler());
            break;
    }*/


    //使用自己封装的request  传入
    $fransRequest = Request::init($request);
    $fransResponse = Response::init($response);

    $routeInfo = $dispatcher->dispatch($fransRequest->getMethod(), $fransRequest->getUri());
    switch ($routeInfo[0]) {
        case FastRoute\Dispatcher::NOT_FOUND:
            $response->status(404);
            $response->end("Method not found");
            break;
        case FastRoute\Dispatcher::METHOD_NOT_ALLOWED:
            $response->status(405);
            $response->end("Method not allow");

            break;
        case FastRoute\Dispatcher::FOUND:
            $handler = $routeInfo[1];
            //file_put_contents(__DIR__ . '/' . date('Ymd') . '.log', __METHOD__ . " handler:" . json_encode($routeInfo) . "\r\n\n", FILE_APPEND);

            file_put_contents(__DIR__ . '/' . date('Ymd') . '.log', __METHOD__ . " router args:" . json_encode($routeInfo[2]) . "\r\n\n", FILE_APPEND);

            $bind_params = $routeInfo[2];
            $ext_params = [$fransRequest, $fransResponse];
            $data = $handler($bind_params, $ext_params);
            //file_put_contents(__DIR__ . '/' . date('Ymd') . '.log', __METHOD__ . " response :" . $data . "\r\n\n", FILE_APPEND);

            $fransResponse->setBody("输出的结果是：" . $data); //设置body体
            $fransResponse->end();
            break;
    }


});
$server->start();